//
//  PersonalCenterView.m
//  SouthChina
//
//  Created by kc on 15/7/1.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "PersonalCenterView.h"
#import "PersonalCenterTableViewCell.h"
#import "PersonalInforViewController.h"
#import "SetViewController.h"
#import "AboutViewController.h"
#import "WorkStateViewController.h"
#import "AddButtonPullDownView.h"
#import "AddFriendViewController.h"
#import "ZbarReaderViewController.h"
#import "FeedbackViewController.h"
#import "TouristViewController.h"
#import "CreateGroupViewController.h"
#import "QRcodeViewController.h"

@interface PersonalCenterView()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIAlertViewDelegate>{
    NSArray *Poptitles; //弹出菜单标题
    NSArray *titlespic; //标题图片
}

@property (strong, nonatomic) IBOutlet UIView *infoview;
@property (strong, nonatomic) IBOutlet UIImageView *qrImage; //个人二维码
@property (strong, nonatomic) IBOutlet UILabel *studentnuber; //学工号
@property (strong, nonatomic) IBOutlet UILabel *username; //用户名
@property (strong, nonatomic) IBOutlet UIImageView *imageHead;//用户头像
@property (strong, nonatomic) IBOutlet UITableView *tabView;
@property (strong, nonatomic) IBOutlet NSArray * titles; //标题列表
@end
@implementation PersonalCenterView

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeWorkStatus:) name:CHANGE_WORK_STATUS object:nil];
        
    }
    return self;
}

- (void)ChangeWorkStatus:(NSNotification *)notification{
    NSLog(@"ChangeWorkStatus %@",notification.object);
    if(notification.object !=nil)
        [self showAlerHUD:notification.object];
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImageEX:[UIImage imageNamed:@""]  text:text hudWidth:150.0f];
    hudex.center = CGPointMake(self.view.center.x,self.view.center.y+210);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.0 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleBarWithBackBtn:@"我" needReturn:NO];
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"PersonalCenterViewBody" owner:self options:nil] objectAtIndex:0];
    //viewBody.frame = (CGRect){0, self.titlebar.frame.origin.y+self.titlebar.frame.size.height,SCREEN_WIDTH, SCREEN_HEIGHT-self.titlebar.frame.size.height};
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    // [self.view addSubview:bodyView];
    [self.view addSubview:viewBody];
    _tabView.delegate = self;
    _tabView.dataSource = self;
    _tabView.bounces = YES
    ;
    
    //获取登陆用户名
    NSString * strName = [NSString stringWithFormat:@"%@(%@)",[DE getGlobalVar:LOGIN_USER_NAME] == nil?@"":[DE getGlobalVar:LOGIN_USER_NAME],[[DE getGlobalVar:LOGIN_USER_TYPE] isEqualToString:@"T"]?@"教职工":@"学生"];
    NSLog(@"用户类型：%@。。。。。%@",[DE getGlobalVar:LOGIN_USER_TYPE],strName);
    _username.text = strName;
    //获取学工号
    NSString *jobnumber = [DE getGlobalVar:LOGIN_USER_REALUSERID] == nil?@"":[DE getGlobalVar:LOGIN_USER_REALUSERID];
    _studentnuber.text =[[NSString alloc] initWithFormat:@"学工号：%@",jobnumber];
    //用户头像
    NSString *headStr = [DE getGlobalVar:LOGIN_USER_HEADIMG] == nil?@"":[DE getGlobalVar:LOGIN_USER_HEADIMG];
    NSURL *url= [NSURL URLWithString: [headStr hasPrefix:@"http"]?headStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,headStr]];
    
    [_imageHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    _imageHead.layer.masksToBounds = YES;
    _imageHead.layer.cornerRadius = 21;
    
    //uiview增加响应事件
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickpersonalinfo)];
    [ _infoview addGestureRecognizer:singleTap];
    
    //个人二维码增加点击事件
    _qrImage.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapqrimage =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickqrImage)];
    [_qrImage addGestureRecognizer:tapqrimage];
    
    
    //标题
    // _titles = @[@[@"我的收藏",@"我的工作状态",@"公众号管理",@"个性主题"],@[@"设置",@"关于"],@[@"注销",@"退出"]];
    //暂时保留下面几项
    _titles = @[@[@"我的工作状态"],@[@"设置",@"关于"],@[@"退出"]];
    titlespic = @[@[@"chat.png"],@[@"icon_setting.png",@"icon_about.png"],@[@"icon_exit.png"]];
    [self refreshTableView];
    
    //标题栏增加右键按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(258.0f, (YNEW), 60.0f, 40.0f);
    [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"addfriend_group_flag"] forState:UIControlStateNormal];
    // rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
    [self.titlebar addSubview:rightBtn];
    Poptitles = @[@"添加朋友",@"扫一扫",@"意见反馈"];
    
}

//弹出二维码视图
-(void) onClickqrImage
{
    NSLog(@"点击二维码图片事件");
    NSDictionary *map = @{};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"getUserQrCode" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            [self setQrCode:[data objectForKey:@"qrCodeSrc"]];
        }
        else{
            [self showAlerHUD:@"获取个人二维码失败！"];
        }
    }];
}

-(void)setQrCode:(NSString *)str
{
    QRcodeViewController *qrcodeimg = [[QRcodeViewController alloc] init];
    NSLog(@"URL:%@",str);
    qrcodeimg.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        qrcodeimg.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }else{
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    qrcodeimg.strurl = str;
    [self presentViewController:qrcodeimg animated:YES completion:^{
        NSLog(@"present成功，从ViewController切换到QRcodeViewController");}];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//个人信息
-(void) clickpersonalinfo
{
    PersonalInforViewController * personalinformation = [[PersonalInforViewController alloc] init];
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:personalinformation animated:NO ];
}

//返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _titles.count;
}

//每个分区多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arrList = [_titles objectAtIndex:section];
    return  arrList.count;
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 26;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;//不要返回0，返回0的话，设置无效果
}



//设置每行的显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*static NSString * CellIdentifier = @"Cell";
     UITableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
     if (!cell) {
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
     }
     cell.textLabel.font = [UIFont systemFontOfSize:14];
     // cell.textLabel.textColor = [UIColor colorWithRed:105.0/255 green:105.0/255 blue:105.0/255 alpha:1];
     cell.textLabel.text = _titles[indexPath.section][indexPath.row];*/
    
    static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
    PersonalCenterTableViewCell *cell = [[PersonalCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    if(indexPath.section!=0)
    {
        UIImageView *cellimage =  [[UIImageView alloc] initWithFrame:CGRectMake(15, 18,20, 20)];
        UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(48, 18, 100, 20)];
        cellimage.image = [UIImage imageNamed:titlespic[indexPath.section][indexPath.row]];
        titlaLabel.text = _titles[indexPath.section][indexPath.row];
        [cell addSubview:cellimage];
        titlaLabel.textAlignment = NSTextAlignmentLeft;
        titlaLabel.font = [UIFont systemFontOfSize:14];
        [cell addSubview:titlaLabel];
    }
    else
    {
        UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 18, 100, 20)];
        titlaLabel.text = _titles[indexPath.section][indexPath.row];
        titlaLabel.textAlignment = NSTextAlignmentLeft;
        titlaLabel.font = [UIFont systemFontOfSize:14];
        [cell addSubview:titlaLabel];
    }
    
    
    return cell;
}

-(void) refreshTableView{
    //获取登陆用户名
    NSString * strName = [NSString stringWithFormat:@"%@(%@)",[DE getGlobalVar:LOGIN_USER_NAME] == nil?@"":[DE getGlobalVar:LOGIN_USER_NAME],[[DE getGlobalVar:LOGIN_USER_TYPE] isEqualToString:@"T"]?@"教职工":@"学生"];
    NSLog(@"用户类型：%@。。。。。%@",[DE getGlobalVar:LOGIN_USER_TYPE],strName);
    
    _username.text = strName;
    
    //用户头像
    NSString *headStr = [DE getGlobalVar:LOGIN_USER_HEADIMG] == nil?@"":[DE getGlobalVar:LOGIN_USER_HEADIMG];
    NSURL *url= [NSURL URLWithString: [headStr hasPrefix:@"http"]?headStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,headStr]];
    
    [_imageHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
}

-(void)showRightBtnView:(id)sender
{
    CGFloat xWidth = self.view.bounds.size.width - 162.0f;
    CGFloat yHeight = 120.0f;
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, xWidth, yHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = YES;
    poplistview.center = CGPointMake(240,130);
    [poplistview show];
}

#pragma mark - UIPopoverListViewDataSource

- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView
                    cellForIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    
    cell.textLabel.text = Poptitles[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
    return cell;
}

- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section
{
    return Poptitles.count;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section==0)
    {
        if(indexPath.row==0) //添加朋友
        {
            AddFriendViewController * addfriend = [[AddFriendViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:addfriend animated:NO];
        }else if(indexPath.row==1)//扫一扫
        {
            ZbarReaderViewController * scanning = [[ZbarReaderViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanning animated:NO];
        }else if(indexPath.row==2)//意见反馈
        {
            FeedbackViewController * feedback = [[FeedbackViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:feedback animated:NO];
        }
    }
}
- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

//响应事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"did selectrow");
    if(indexPath.section==0)
    {
        if (indexPath.row == 0) {
            WorkStateViewController * workinfoview = [[WorkStateViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:workinfoview animated:NO ];
        }
    }
    else if(indexPath.section==1){
        if(indexPath.row==0) //设置
        {
            SetViewController * setviewcontroller = [[SetViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:setviewcontroller animated:NO ];
            
        }
        else{             //关于
            AboutViewController * about = [[AboutViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:about animated:NO];
        }
    }
    else{
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要退出吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 101;
            [alert show];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 101) {
        exit(1);
    }
    else if (buttonIndex == 1 && alertView.tag == 102)
    {
        
        [MBProgressHUD showHUDAddedTo:self.view prompt:@"正在登出..." animated:YES];
        NSDictionary *dict = [[NSDictionary alloc] init];
        [DE serverCall:@"loginOut" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [DE unload];
            
            DE.userId=@"";
            DE.userPassword=@"";
            [DE setGlobalVar:LOGIN_USER_ID value:@""];
            kAppDelegate.mqttState = MQTT_NO_CONNECT;
            [DE setGlobalVar:LOGIN_USER_PASSWORD value:@""];
            
            TouristViewController *info = [[TouristViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController setViewControllers:@[info] animated:YES];
        }];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    //获取登陆用户名
    NSString * strName = [NSString stringWithFormat:@"%@(%@)",[DE getGlobalVar:LOGIN_USER_NAME] == nil?@"":[DE getGlobalVar:LOGIN_USER_NAME],[[DE getGlobalVar:LOGIN_USER_TYPE] isEqualToString:@"T"]?@"教职工":@"学生"];
    NSLog(@"用户类型：%@。。。。。%@",[DE getGlobalVar:LOGIN_USER_TYPE],strName);
    
    _username.text = strName;
    
    //用户头像
    NSString *headStr = [DE getGlobalVar:LOGIN_USER_HEADIMG] == nil?@"":[DE getGlobalVar:LOGIN_USER_HEADIMG];
    NSURL *url= [NSURL URLWithString: [headStr hasPrefix:@"http"]?headStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,headStr]];
    
    [_imageHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
}

@end
